// pages/register/register.js
var app = getApp();
var util = require('../../utils/util');
var interval = null //倒计时函数
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goods_image: "",
        username: "",
        time: '获取验证码', //倒计时 
        currentTime: 60, //限制60s
        isClick: false, //获取验证码按钮，默认允许点击
        uploadControls: {
            store_header: {
                name: "上传照片",
                image: "/images/updat.png",
                tag: "store_header"
            },
            business_images: {
                name: "上传照片",
                image: "/images/updat.png",
                tag: "business_images"
            },
            card_pros: {
                name: "上传照片",
                image: "/images/updat.png",
                tag: "card_pros"
            },
            card_cons: {
                name: "上传照片",
                image: "/images/updat.png",
                tag: "card_cons",
            },
            food_ok_image: {
                name: "上传照片",
                image: "/images/updat.png",
                tag: "food_ok_image"
            }
        },
        allImg: {},
        address: "",
        ischecked: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // console.log(options,"kjsdfklsdajfklsajfkl商户用户ID");
        if (options.q != undefined) {
            let q = util.getJson(decodeURIComponent(options.q));
            console.log(q, "klsdjflksjfkl");
            this.setData({
                inv_id: q.inv_id
            })
            console.log(this.data.inv_id, "111111111111111")
        }
		//用来判断是不是重新注册
		if (options.id != undefined) {
			this.setData({
				id: options.id
			})
		}
        this.getClassList();
		this.storeInv();

    },

	//初始化绑定邀请关系
	storeInv:function(e){
		var that=this;
		var apiUrl = '/api/store/login/bind_store_inv';
		
		wx.login({
			success(res) {
				if (res.code) {
					//发起网络请求
					util.fetchPost(apiUrl,{
						js_code:res.code,
						inv_member_id: that.data.inv_id == undefined ? 0 : that.data.inv_id
					}, function (res) {
						util.hideLoading();
					});
				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		})

	},
    //获取用户地理位置权限
    addresTap: function() {
		var that=this;
        wx.chooseLocation({
            success: function(res) {

                that.setData({
                    address: res //调用成功直接设置地址
                })
            },
            fail: function() {
                wx.getSetting({
                    success: function(res) {
                        var statu = res.authSetting;
                        if (!statu['scope.userLocation']) {
                            wx.showModal({
                                title: '是否授权当前位置',
                                content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                                success: function(tip) {
                                    if (tip.confirm) {
                                        wx.openSetting({
                                            success: function(data) {
                                                if (data.authSetting["scope.userLocation"] === true) {
                                                    wx.showToast({
                                                        title: '授权成功',
                                                        icon: 'success',
                                                        duration: 1000
                                                    })
                                                    //授权成功之后，再调用chooseLocation选择地方
                                                    wx.chooseLocation({
                                                        success: function(res) {
                                                            that.setData({
                                                                address: res
                                                            })
                                                        },
                                                    })
                                                } else {
                                                    wx.showToast({
                                                        title: '授权失败',
                                                        icon: 'success',
                                                        duration: 1000
                                                    })
                                                }
                                            }
                                        })
                                    }
                                }
                            })
                        }
                    },
                    fail: function(res) {
                        wx.showToast({
                            title: '调用授权窗口失败',
                            icon: 'success',
                            duration: 1000
                        })
                    }
                })
            }
        })
    },

    //单选按钮
    pwdChecked: function(e) {
        this.data.ischecked = !this.data.ischecked;
        this.setData({
            ischecked: this.data.ischecked
        })
        //   console.log(this.data.username, password);
    },
    /**
     * 用户手机号
     * */
    usernameInput: function(event) {
        // console.log("username==",event.detail.value)
        this.setData({
            username: event.detail.value
        })
    },
    /**
     * 获取验证码
     */
    gainAuthCodeAction: function() {
        let that = this;
        /*第一步：验证手机号码*/
        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
        if (that.data.username.length == 0) {
            util.showSuccess('手机号码不能为空', 'none', false, 800);
            return;
        }

        if (that.data.username.length < 11) {
            util.showSuccess('手机号码长度有误！', 'none', false, 800);
            return;
        }

        if (!myreg.test(that.data.username)) {
            util.showSuccess('错误的手机号码！', 'none', false, 800);
            return;
        }
        /*第二步：设置计时器*/
        // 先禁止获取验证码按钮的点击
        that.setData({
            isClick: true,
        })
        // 60s倒计时 setInterval功能用于循环，常常用于播放动画，或者时间显示
        var currentTime = that.data.currentTime;
        interval = setInterval(function() {
            currentTime--; //减
            that.setData({
                time: currentTime + '秒后获取'
            })
            if (currentTime <= 0) {
                clearInterval(interval)
                that.setData({
                    time: '获取验证码',
                    currentTime: 60,
                    isClick: false
                })
            }
        }, 1000);
        /*第三步：请求验证码接口，并记录服务器返回的验证码用于判断，这里服务器也可能不返回验证码，那验证码的判断交给后台*/
        // wx.request({})
        var apiUrl = '/api/v1/common/identifying_code';
        var apiData = {
            phone: that.data.username
        }
        util.fetchPost(apiUrl, apiData, function(res) {
            util.hideLoading();
            if (res.state == 1) {

            } else {
                util.message(res.datas);
            }
        });
    },

    //图片上传
    onFilePathTap: function(e) {
        var that = this;
        var tag = e.currentTarget.dataset.tag;
        util.showLoading();
        wx.chooseImage({
            count: 1,
            success(res) {
                const tempFilePaths = res.tempFilePaths
                wx.uploadFile({
                    url: app.globalData.http_url + '/api/v1/common/upload',
                    header: {
                        'Content-Type': 'multipart/form-data'
                    },
                    filePath: tempFilePaths[0],
                    name: 'file',
                    formData: {
                        key: app.globalData.key
                    },
                    success: function(result) {
                        util.hideLoading();
                        var res = JSON.parse(result.data);
                        if (res.code != 1) {
                            wx.showToast({
                                title: '上传失败',
                                icon: 'none'
                            });
                            return false;
                        }
                        console.log(res)
                        console.log(tag)
                        var allImg = that.data.allImg;
                        switch (tag) {
                            case "store_header":
                                allImg["store_header"] = {
                                    id: res.id,
                                    path: res.path
                                }
                                break;
                            case "business_images":
                                allImg["business_images"] = {
                                    id: res.id,
                                    path: res.path
                                };
                                break;
                            case "card_pros":
                                allImg["card_pros"] = {
                                    id: res.id,
                                    path: res.path
                                };
                                break;
                            case "card_cons":
                                allImg["card_cons"] = {
                                    id: res.id,
                                    path: res.path
                                };
                                break;
                            case "food_ok_image":
                                allImg["food_ok_image"] = {
                                    id: res.id,
                                    path: res.path
                                };
                                break;
                        }
                        that.setData({
                            allImg: allImg
                        })
                        console.log(that.data.allImg)

                    },
                    fail: function(res) {
                        utils.hideLoading();
                        utils.message('上传服务器上传失败,请稍后再试');
                        console.log(res);
                    }
                })
            }
        })
    },
    //删除照片
    onCloseImgTap: function(e) {
        var that = this;
        var tag = e.currentTarget.dataset.tag;
        var allImg = that.data.allImg;
        //	console.log(tag == allImg[tag],tag,allImg[tag])
        delete allImg[tag]
        that.setData({
            allImg: allImg
        })
        console.log(that.data.allImg)
    },
    //打印机种类
    getClassList: function() {
        var that = this;
        util.showLoading();
        util.fetchPost("/api/v1/common/print_list", {}, function(res) {
            if (res.state == 1) {
                var array = [];
                for (var i in res.datas) {
                    array.push(res.datas[i].name)
                }
                that.setData({
                    array: array,
                    index: 0,
                    classlist: res.datas,
                })
            } else {
                util.message(res.datas)
            }
        })
        util.hideLoading();
    },
    //选择打印机种类
    bindPickerChange: function(e) {
        this.setData({
            index: e.detail.value,
        });
    },
    //提交
    formSubmit: function(e) {
        console.log(e);
        var that = this;
        var bank_code = e.detail.value.bank_code;
        var bank_name = e.detail.value.bank_name;
        var cardholder = e.detail.value.cardholder;
        var code = e.detail.value.code;
        var map_address = e.detail.value.map_address;
        var print_key = e.detail.value.print_key;
        var print_sn = e.detail.value.print_sn;
        var store_name = e.detail.value.store_name;
        var username = e.detail.value.username;
        var allImg = that.data.allImg;
        if (store_name == "") {
            util.showSuccess('请输入商家店名', 'none', false, 800);
            return false;
        }
        var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; // 判断手机号码的正则
        if (username.length == 0) {
            util.showSuccess('手机号码不能为空', 'none', false, 800);
            return;
        }

        if (username.length < 11) {
            util.showSuccess('手机号码长度有误！', 'none', false, 800);
            return;
        }

        if (!myreg.test(username)) {
            util.showSuccess('错误的手机号码！', 'none', false, 800);
            return;
        }
        if (code == "") {
            util.showSuccess('请输入验证码', 'none', false, 800);
            return false;
        }
        if (that.data.address == "") {
            util.showSuccess('请选择店铺地址', 'none', false, 800);
            return false;
        }
        if (map_address == "") {
            util.showSuccess('请输入详细地址地址', 'none', false, 800);
            return false;
        }
        if (cardholder == "") {
            util.showSuccess('请输入持卡人姓名', 'none', false, 800);
            return false;
        }
        if (bank_code == "") {
            util.showSuccess('请输入银行卡号', 'none', false, 800);
            return false;
        }
        if (bank_name == "") {
            util.showSuccess('请输入开户行', 'none', false, 800);
            return false;
        }

        if (print_sn == "") {
            util.showSuccess('请输入打印机编号', 'none', false, 800);
            return false;
        }
        if (print_key == "") {
            util.showSuccess('请输入打印机秘钥', 'none', false, 800);
            return false;
        }
        if (allImg.store_header == undefined) {
            util.showSuccess('请上传店铺头像', 'none', false, 800);
            return false;
        }
        if (allImg.business_images == undefined) {
            util.showSuccess('请上传营业执照', 'none', false, 800);
            return false;
        }
		if (allImg.food_ok_image == undefined) {
			util.showSuccess('请上传食品生产许可证', 'none', false, 800);
			return false;
		}
        if (allImg.card_pros == undefined) {
            util.showSuccess('请上传正面照', 'none', false, 800);
            return false;
        }
        if (allImg.card_cons == undefined) {
            util.showSuccess('请上传反面照', 'none', false, 800);
            return false;
        }

        
        if (that.data.ischecked == false) {
            util.showSuccess('请同意 《用户协议及隐私政策》', 'none', false, 800);
            return false;
        }
        util.showLoading();
        
        
		wx.login({
			success(res) {
				if (res.code) {
					if (that.data.id) {
						var apiUrl = '/api/store/login/again_register_v2';
						var apiData = {
							store_name: store_name,
							username: username,
							code: code,
							map_address: that.data.address.address + '' + map_address,
							longitude: that.data.address.longitude,
							latitude: that.data.address.latitude,
							cardholder: cardholder,
							bank_code: bank_code,
							bank_name: bank_name,
							print_type: that.data.classlist[that.data.index].id,
							print_sn: print_sn,
							print_key: print_key,
							store_pic: allImg.store_header.id,
							business_license: allImg.business_images.id,
							id_image_zheng: allImg.card_pros.id,
							id_image_fan: allImg.card_cons.id,
							food_ok_image: allImg.food_ok_image.id,
							inv_id: that.data.inv_id,
							js_code: res.code,
							id: that.data.id
						}
					} else {
						var apiUrl = '/api/store/login/register_v2';
						var apiData = {
							store_name: store_name,
							username: username,
							code: code,
							map_address: that.data.address.address + '' + map_address,
							longitude: that.data.address.longitude,
							latitude: that.data.address.latitude,
							cardholder: cardholder,
							bank_code: bank_code,
							bank_name: bank_name,
							print_type: that.data.classlist[that.data.index].id,
							print_sn: print_sn,
							print_key: print_key,
							store_pic: allImg.store_header.id,
							business_license: allImg.business_images.id,
							id_image_zheng: allImg.card_pros.id,
							id_image_fan: allImg.card_cons.id,
							food_ok_image: allImg.food_ok_image.id,
							inv_id: that.data.inv_id,
							js_code: res.code,
						}
					}
					
					util.fetchPost(apiUrl, apiData, function (res) {
						util.hideLoading();
						if (res.state == 1) {
							util.showSuccess('注册成功');
							wx.reLaunch({
								url: '../login/login',
							})
						} else {
							util.message(res.datas);
						}
					});
				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		})
        

    },
    //进入协议详情
    detilxieyiTap: function(e) {
        wx.navigateTo({
            url: '../detils/detils',
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})